/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="gis-devicePanel">
    <div class="title">{{this.$t('openatc.gis.deviceState') }}</div>
    <div>
      <div class="filters">
        <el-input
          clearable
          v-model="devsfilter"
          :placeholder="$t('openatc.common.searchplaceholder')"
          prefix-icon="el-icon-search"
          style="width: 200px;margin-right: 10px;"/>
        <el-button type="primary" @click="getDeviceRanges()">{{
              $t("openatc.common.search")
            }}</el-button>
      </div>
      <div class="devicePanel">
        <el-table
          ref="singleTable"
          class="deviceTable"
          :data="devicesTableData"
          row-key="id"
          @cell-mouse-enter="enterSelectionRows"
          @cell-mouse-leave="leaveSelectionRows"
          :max-height="maxHeight"
          highlight-current-row
          @current-change="handleCurrentRowChange"
          @row-click="onRowClick"
          v-loading.body="listLoading"
          v-loading="listLoading"
          element-loading-spinner="el-icon-loading"
          :element-loading-background="loadingBg"
          style="width: 100%"
        >
          <el-table-column type="index" label="#" align="center" width="80">
          </el-table-column>
          <!-- <el-table-column
            prop="agentid"
            :label="$t('openatc.devicemanager.crossid')"
            align="center"
            width="130"
          >
          </el-table-column> -->
          <el-table-column
            prop="name"
            :label="$t('openatc.greenwaveoptimize.devicename')"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="roles"
            :label="$t('openatc.devicemanager.state')"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <div>
                <el-tag
                  size="medium"
                  effect="plain"
                  :type="getTag(scope.row).type"
                  >{{ getTag(scope.row).label }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('openatc.greenwaveoptimize.operation')"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="onDetailClick(scope.row)">{{
                $t("openatc.common.configurationparameter")
              }}</el-button>
              <el-button type="text" @click="handleLook(scope.row)">{{
                $t("openatc.common.look")
              }}</el-button>
              <el-button type="text" @click="handleEdit(scope.row)">{{
                $t("openatc.common.locationEdit")
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination  @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="listQuery.pageNum"
                        :page-size="listQuery.pageRow"
                        :total="totalCount"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="total, sizes, prev, pager, next">
        </el-pagination>
      </div>
    </div>
    <Update ref="updateChild"></Update>
    <EdgeModal ref="edgeModalChild"></EdgeModal>
    <RoadModel ref="roadModalChild"></RoadModel>
    <router-view></router-view>
  </div>
</template>
<script>
// import router from '../../router'
import L from 'leaflet'
import { GetAllDevice, getDeviceRange } from '../../../../api/device'
import Update from './update'
import EdgeModal from './edgeModal'
import RoadModel from './roadModel'
import XRDDirSelector from '../../../../components/XRDDirSelector'
import { getMessageByCode } from '../../../../utils/responseMessage'
import { getTheme } from '../../../../utils/auth'
// import PhaseMarkerVue from './index'
export default {
  name: 'device',
  components: { Update, EdgeModal, RoadModel, XRDDirSelector },
  props: {
    deviceList: {
      type: Array
    }
  },
  watch: {
    deviceList (val) {
      this.onDeviceListChange(val)
    }
  },
  data () {
    return {
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 50 // 每页条数
      },
      devsfilter: '',
      totalCount: 0, // 分页组件--数据总条数
      loadingBg: getTheme() === 'light' ? '#fff' : '#202940',
      maxHeight: screen.height - 425,
      map: null,
      lngLat: {
        lng: '0.00000000',
        lat: '0.00000000'
      },
      editDevicevisible: false,
      devicesTableData: [],
      messageboxVisible: false,
      listLoading: false, // 表格数据加载等待动画
      curDevice: undefined, // 当前所选设备信息
      loading: false,
      deviceFaultIcon: require('../../../../assets/gis/devicefault.png'),
      deviceOnlineIcon: require('../../../../assets/gis/deviceonline.png'),
      deviceNotOnlineIcon: require('../../../../assets/gis/devicenotonline.png'),
      deviceLayer: null,
      devList: []
    }
  },
  mounted () {
    let _this = this
    this.$nextTick(() => {
      _this.getAllAdevice()
      _this.getDeviceRanges()
    })
  },
  destroyed () {
    this.hideLayer()
  },
  methods: {
    onDeviceListChange (list) {
      this.devList = list
      this.map = window.map
      this.handleMapDevice(this.devList)
    },
    // 鼠标进入表格行的回调函数
    enterSelectionRows (row, column, cell, event) {
      if (!row.hasAuth) {
        this.createTips(event, row, this.$t('openatc.devicemanager.crossid') + ':' + row.agentid)
      }
    },
    // 鼠标离开表格行的回调函数
    leaveSelectionRows (row) {
      this.removeTips(row)
    },

    // 创建toolTip
    createTips (el, row, value) {
      const { id } = row
      const tooltipDom = document.createElement('div')
      tooltipDom.style.cssText = `
            display: inline-block;
            max-width: 400px;
            max-height: 400px;
            position: absolute;
            top: ${el.clientY + 5}px;
            left: ${el.clientX + 5}px;
            padding:5px 10px;
            overflow: auto;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #595959;
            background: #fff;
            z-index: 19999;
          `
      tooltipDom.innerHTML = value
      tooltipDom.setAttribute('id', `tooltip-${id}`)
      // 将浮层插入到body中
      document.body.appendChild(tooltipDom)
    },

    // 删除tooltip
    removeTips (row) {
      const { id } = row
      const tooltipDomLeave = document.querySelectorAll(`#tooltip-${id}`)
      if (tooltipDomLeave.length) {
        tooltipDomLeave.forEach(dom => {
          document.body.removeChild(dom)
        })
      }
    },
    handleSizeChange (val) {
      // 改变每页数量，默认返回第一页
      this.listQuery.pageNum = 1
      this.listQuery.pageRow = val
      this.getDeviceRanges()
    },
    handleCurrentChange (val) {
      // 改变页码
      this.listQuery.pageNum = val
      this.getDeviceRanges()
    },
    handleKeywordChange (val) {
      this.getDeviceRanges()
    },
    getDeviceRanges () {
      this.listLoading = true
      let reqData = {
        'pageNum': this.listQuery.pageNum,
        'pageRow': this.listQuery.pageRow,
        'search': this.devsfilter,
        'type': '',
        'platform': '',
        'protocol': '',
        'state': '',
        'code': '',
        'control': -1,
        'mode': -1,
        'tags': ''
      }
      let list = []
      getDeviceRange(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false
        if (res.data.data.content) {
          list = res.data.data.content
        } else {
          list = []
        }
        this.devicesTableData = list
        this.totalCount = res.data.data.total
      })
    },
    getAllAdevice () {
      GetAllDevice().then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devList = res.data.data
        this.map = window.map
        this.handleMapDevice(this.devList)
      })
    },
    handleMapDevice (devs) {
      if (this.deviceLayer) {
        this.deviceLayer.clearLayers()
      }
      let markers = []
      for (let dev of devs) {
        if (!dev.geometry || !dev.geometry.coordinates || dev.geometry.coordinates.length === 0 || dev.geometry.coordinates[0] === 0) {
          continue
        }
        let coordinates = dev.geometry.coordinates
        let devPoint = [coordinates[1], coordinates[0]]
        let iconUrl = this.deviceFaultIcon
        if (dev.state === 'UP') {
          iconUrl = this.deviceOnlineIcon
        } else if (dev.state === 'DOWN') {
          iconUrl = this.deviceNotOnlineIcon
        }
        let notOnlineIcon = L.icon({
          iconUrl: iconUrl,
          iconSize: [42, 31],
          title: dev.state,
          alt: dev,
          iconAnchor: [12, 27]
        })
        let marker = L.marker(devPoint, { icon: notOnlineIcon }).on('click', this.onMarkerClick)
        // 添加marker来设置点击事件
        markers.push(marker)
      }
      this.deviceLayer = L.layerGroup(markers)
      this.map.addLayer(this.deviceLayer)
      this.addMessage()
    },
    handleLook (row) {
      const dev = row
      let roadModalChild = this.$refs.roadModalChild
      roadModalChild.openEdge(dev)
    },
    onMarkerClick (e) {
      let dev = e.target.options.icon.options.alt
      let row = this.devList.filter(item => item.id === dev.id)[0]
      let roadModalChild = this.$refs.roadModalChild
      roadModalChild.openEdge(row)
      this.setCurrent(row)
      // let htmlStr =
      //   `
      //     <div id="test1">
      //     </div>
      //   `
      // let coordinates = row.geometry.coordinates.slice().reverse()
      // let iconAnchor = [coordinates[0] + 110, coordinates[1] - 20]
      // let icon = L.divIcon({
      //   html: htmlStr,
      //   iconSize: [80, 80],
      //   iconAnchor: iconAnchor,
      //   className: 'map-circle'
      // })
      // L.marker(coordinates, {icon: icon}).addTo(this.deviceLayer)
      // let dom = new PhaseMarkerVue({})
      // dom.$mount(`#test1`)

      // var svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
      // svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
      // svgElement.setAttribute('viewBox', '0 0 2000 200')
      // svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>'
      // var svgElementBounds = [coordinates, [coordinates[0] + 20, coordinates[1] + 20]]
      // L.svgOverlay(svgElement, svgElementBounds).addTo(this.deviceLayer)

      // var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg'
      // let imageBounds = [coordinates, [coordinates[0] + 20, coordinates[1] + 20]]
      // L.imageOverlay(imageUrl, imageBounds).addTo(this.deviceLayer)
    },
    addMessage () {
      let _this = this
      this.deviceLayer.eachLayer(function (layer) {
        let options = layer.options.icon.options
        let devData = options.alt
        let content = _this.getPopupContent(devData)
        layer.bindPopup(content)
      })
    },
    getMode (row) {
      if (row.control === 0) {
        return {
          label: this.$t('openatccomponents.overview.modelList0'),
          type: 'success'
        }
      } else if (row.control === 1) {
        return {
          label: this.$t('openatccomponents.overview.modelList1'),
          type: 'warning'
        }
      } else if (row.control === 2) {
        return {
          label: this.$t('openatccomponents.overview.modelList2'),
          type: 'warning'
        }
      } else if (row.control === 3) {
        return {
          label: this.$t('openatccomponents.overview.modelList3'),
          type: 'warning'
        }
      } else if (row.control === 4) {
        return {
          label: this.$t('openatccomponents.overview.modelList4'),
          type: 'warning'
        }
      } else if (row.control === 22) {
        return {
          label: this.$t('openatccomponents.overview.modelList22'),
          type: 'warning'
        }
      } else if (row.control === 5) {
        return {
          label: this.$t('openatccomponents.overview.modelList5'),
          type: 'success'
        }
      } else if (row.control === 6) {
        return {
          label: this.$t('openatccomponents.overview.modelList6'),
          type: 'success'
        }
      } else if (row.control === 7) {
        return {
          label: this.$t('openatccomponents.overview.modelList7'),
          type: 'success'
        }
      } else if (row.control === 8) {
        return {
          label: this.$t('openatccomponents.overview.modelList8'),
          type: 'success'
        }
      } else if (row.control === 9) {
        return {
          label: this.$t('openatccomponents.overview.modelList9'),
          type: 'success'
        }
      } else if (row.control === 10) {
        return {
          label: this.$t('openatccomponents.overview.modelList10'),
          type: 'success'
        }
      } else if (row.control === 11) {
        return {
          label: this.$t('openatccomponents.overview.modelList11'),
          type: 'success'
        }
      } else if (row.control === 12) {
        return {
          label: this.$t('openatccomponents.overview.modelList12'),
          type: 'success'
        }
      } else if (row.control === 13) {
        return {
          label: this.$t('openatccomponents.overview.modelList13'),
          type: 'success'
        }
      } else if (row.control === 14) {
        return {
          label: this.$t('openatccomponents.overview.modelList14'),
          type: 'success'
        }
      } else if (row.control === 15) {
        return {
          label: this.$t('openatccomponents.overview.modelList15'),
          type: 'success'
        }
      } else if (row.control === 16) {
        return {
          label: this.$t('openatccomponents.overview.modelList16'),
          type: 'success'
        }
      } else if (row.control === 17) {
        return {
          label: this.$t('openatccomponents.overview.modelList17'),
          type: 'success'
        }
      } else if (row.control === 18) {
        return {
          label: this.$t('openatccomponents.overview.modelList18'),
          type: 'success'
        }
      } else if (row.control === 19) {
        return {
          label: this.$t('openatccomponents.overview.modelList19'),
          type: 'success'
        }
      } else if (row.control === 21) {
        return {
          label: this.$t('openatccomponents.overview.modelList21'),
          type: 'success'
        }
      } else if (row.control === 23) {
        return {
          label: this.$t('openatccomponents.overview.modelList23'),
          type: 'success'
        }
      } else if (row.control === 24) {
        return {
          label: this.$t('openatccomponents.overview.modelList24'),
          type: 'success'
        }
      } else if (row.control === 99) {
        return {
          label: this.$t('openatccomponents.overview.modelList25'),
          type: 'success'
        }
      } else if (row.control === 100) {
        return {
          label: this.$t('openatccomponents.overview.modelList100'),
          type: 'success'
        }
      } else if (!row.control) {
        return {
          label: '',
          type: ''
        }
      }
    },
    getPopupContent (devData) {
      // let agentid = devData.agentid
      let crossRoadName = devData.name
      let control = this.getMode(devData).label
      let date = devData.lastTime
      let status = this.$t('openatc.devicemanager.online')
      if (devData.state === 'UP') {
        status = this.$t('openatc.devicemanager.online')
      } else if (devData.state === 'DOWN') {
        status = this.$t('openatc.devicemanager.offline')
      } else {
        status = this.$t('openatc.devicemanager.fault')
      }
      let content =
      `
        <div>${crossRoadName}</div>
        <div>${status} &nbsp;${control}</div>
        <div>${date}</div>
      `
      return content
    },
    getTag (row) {
      if (row.state === 'DOWN') {
        return {
          label: this.$t('openatc.devicemanager.offline'),
          type: 'info'
        }
      } else if (row.state === 'FAULT') {
        return {
          label: this.$t('openatc.devicemanager.fault'),
          type: 'danger'
        }
      } else {
        if (row.status === 0) {
          // 数据从设备端来，暂时写死，0代表正常状态，其余数字均代表一种类型的故障
          return {
            label: this.$t('openatc.devicemanager.online'),
            type: 'success'
          }
        } else {
          return {
            label: this.$t('openatc.devicemanager.fault'),
            type: 'danger'
          }
        }
      }
    },
    handleEdit (row) {
      this.curDevice = row
      let updateChild = this.$refs.updateChild
      updateChild.onUpdateClick(row)
    },
    setNewLocation (lngLat) {
      this.curDevice.lng = lngLat.lng
      this.curDevice.lat = lngLat.lat
      let updateChild = this.$refs.updateChild
      updateChild.onUpdateClick(this.curDevice, true)
    },
    onLocationClick (row) {
      this.setDeviceLocation(row)
      this.$message.info(this.$t('openatc.gis.chooseLocationInfo'))
    },
    setDeviceLocation () {
      this.editMode = true
      let _this = this
      const body = document.querySelector('#map')
      const originStyle = body.style.cursor
      body.style.cursor = 'crosshair'
      // body.style.cursor = url.parse('./001.ico')
      _this.map.on('click', function (e) {
        _this.lngLat.lng = String(e.latlng.lng)
        _this.lngLat.lat = String(e.latlng.lat)
        _this.setNewLocation(_this.lngLat)
        _this.map.off('click')
        body.style.cursor = originStyle
      })
    },
    onDetailClick (row) {
      const dev = row
      let edgeModalChild = this.$refs.edgeModalChild
      sessionStorage.setItem('toSingleEdge', '1')
      edgeModalChild.openSingleEdge(dev)
    },
    getList () {
      this.hideLayer(this.deviceLayer)
      this.getAllAdevice()
    },
    hideLayer () {
      this.map.removeLayer(this.deviceLayer)
    },
    showLayer () {
      this.map.addLayer(this.deviceLayer)
    },
    setCurrent (row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    handleCurrentRowChange (val) {
      this.currentRow = val
    },
    setCurrentMarker (dev) {
      let marker
      let layers = this.deviceLayer._layers
      for (var x in layers) {
        let layer = layers[x]
        if (layer.options.icon.options.alt.id === dev.id) {
          marker = layer
          break
        }
      }
      if (marker) {
        let _latlng = marker._latlng
        this.map.flyTo(_latlng)
        marker.openPopup(_latlng)
      }
    },
    onRowClick (row) {
      this.setCurrentMarker(row)
    }
  }
}
</script>
<style lang="scss" scoped>
  .devicePanel /deep/ .active {
    position: static;
  }
</style>
